# -*- coding: utf-8 -*-

"""
@author: Mark Wu
@file: operationConfig.py
@time: 2025/3/25 21:45
"""

import sys
import traceback
import configparser

from src.conf import setting
from src.common.recordlog import logs


class OperationConfig:
    """封装读取*.ini配置文件模块"""
    def __init__(self, filepath=None):
        if filepath is None:
            self.filepath = setting.FILE_PATH['CONFIG']
        else:
            self.__filepath = filepath
        self.conf = configparser.ConfigParser()
        try:
            self.conf.read(self.filepath, encoding='utf-8')
        except Exception as e:
            exc_type, exc_value, exc_obj = sys.exc_info()
            logs.error(str(traceback.print_exc(exc_obj)))

        self.type = self.get_report_type("type")

    def get_item_value(self, section_name):
        """
        获取配置文件中某个section下的所有option和value
        :param section_name: ini配置文件中section名称
        :return: 以字典形式返回section下所有option和value
        """
        items = self.conf.items(section_name)   # 获得键值对数组
        return dict(items)

    def get_section_for_data(self, section, option):
        try:
            value = self.conf.get(section, option)
            return value
        except Exception as e:
            logs.error(str(traceback.format_exc()))
            return ''

    def write_config_data(self, section, option_key, option_value):
        """
        写入数据到ini配置文件中
        :param section: 头部值
        :param option_key: 选项值key
        :param option_value: 选项值value
        :return:
        """
        if section not in self.conf.sections():
            self.conf.add_section(section)
            self.conf.set(section, option_key, option_value)
        else:
            logs.info('section:{} is exist'.format(section))
        with open(self.filepath, 'w') as fp:
            self.conf.write(fp)

    def get_section_sqlite(self, option):
        return self.get_section_for_data('SQLITE', option)

    def get_section_mysql(self, option):
        return self.get_section_for_data('MYSQL', option)

    def get_section_redis(self, option):
        return self.get_section_for_data('REDIS', option)

    def get_section_clickhouse(self, section):
        return self.get_section_for_data('CLICKHOUSE', section)

    def get_section_mongodb(self, section):
        return self.get_section_for_data('MongoDB', section)

    def get_report_type(self, option):
        return self.get_section_for_data('REPORT_TYPE', option)

    def get_section_ssh(self, option):
        return self.get_section_for_data('SSH', option)


if __name__ == '__main__':
    op = OperationConfig()
    op.get_item_value("MYSQL")


